package com.huaxin.hxcloud.fragment;

import android.app.Dialog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TextInputEditText;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.TextView;

import com.huaxin.common.BaseActivity;
import com.huaxin.common.BaseFragment;
import com.huaxin.common.Entity.BaseDTO;
import com.huaxin.common.utils.DialogUtil;
import com.huaxin.common.utils.StringUtils;
import com.huaxin.common.utils.ToastUtil;
import com.huaxin.common.view.VerifyCodeView;
import com.huaxin.hxcloud.R;
import com.huaxin.hxcloud.activity.ModifyPasswordActivity;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2017/1/12.
 */

public class ModifyPassword2Fragment extends BaseFragment {


    @BindView(R.id.toolbar)
    Toolbar           toolbar;
    @BindView(R.id.tv_tip)
    TextView          tvTip;
    @BindView(R.id.code)
    VerifyCodeView    code;
    @BindView(R.id.bt_regain)
    Button            btRegain;
    @BindView(R.id.tv_count_down)
    TextView          tvCountDown;
    @BindView(R.id.et_password)
    TextInputEditText etPassword;
    @BindView(R.id.et_password_confirm)
    TextInputEditText etPasswordConfirm;
    @BindView(R.id.bt_register)
    Button            btRegister;
    private String _phoneNum;
    private static final int COUNT_START = 0x00;
    private static final int COUNT_DOWN  = 0x01;
    private int _count;
    Handler _handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case COUNT_START:
                    showCount(true);
                    _count = 90;
                    tvCountDown.setText(_count + "s");
                    sendEmptyMessageDelayed(COUNT_DOWN, 1000);
                    break;
                case COUNT_DOWN:
                    _count--;
                    if (_count > 0) {
                        tvCountDown.setText(_count + "s");
                        sendEmptyMessageDelayed(COUNT_DOWN, 1000);
                    } else {
                        showCount(false);
                    }

                    break;
                default:
                    break;
            }
        }
    };


    private void showCount(boolean b) {
        if (b) {
            tvCountDown.setVisibility(View.VISIBLE);
            btRegain.setVisibility(View.GONE);
        } else {
            tvCountDown.setVisibility(View.GONE);
            btRegain.setVisibility(View.VISIBLE);
        }
    }


    @Override
    protected int getContentViewId() {
        return R.layout.fragment_modify_password2;
    }

    @Override
    protected void initView(View view) {
        super.initView(view);
        _phoneNum = ((ModifyPasswordActivity) getActivity()).getPhoneNum();
        tvTip.setText("短信验证码已发送至\n" + _phoneNum + "\n请填写验证码");
        _handler.sendEmptyMessage(COUNT_START);
    }


    @Override
    public void onResumeView() {
        super.onResumeView();
        ((BaseActivity) getActivity()).setSupportActionBar(toolbar);
    }

    public void ApiModifyPassword() {

        final Dialog dialog = DialogUtil.getWaitDialog(getContext(), "发送中...");
        dialog.show();
        Call<BaseDTO> call = getRequestApi().modifyPassword(
                ((ModifyPasswordActivity) getActivity()).getPhoneNum(), etPassword.getText().toString(),
                code.getVerifyCodeStr());
        autoClose(call);
        call.enqueue(new Callback<BaseDTO>() {
            @Override
            public void onResponse(Call<BaseDTO> call, Response<BaseDTO> response) {
                dialog.dismiss();
                BaseDTO baseDTO = response.body();
                if (response.isSuccessful() && baseDTO != null) {
                    if (baseDTO.isSuccessful()) {
                        ToastUtil.showToast("修改成功");
                        getActivity().finish();

                    } else {
                        ToastUtil.showToast(baseDTO.getMsg());
                    }
                } else {
                    ToastUtil.showToast("数据异常");
                }
            }

            @Override
            public void onFailure(Call<BaseDTO> call, Throwable t) {
                dialog.dismiss();
                ToastUtil.showToast("网络故障");
            }
        });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        _handler.removeMessages(COUNT_DOWN);
        hideIme();
    }

    private void hideIme() {
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context
                .INPUT_METHOD_SERVICE);

        if (imm != null && imm.isActive(etPassword)) {
            imm.hideSoftInputFromWindow(etPassword.getWindowToken(), 0);
        }
        if (imm != null && imm.isActive(etPasswordConfirm)) {
            imm.hideSoftInputFromWindow(etPasswordConfirm.getWindowToken(), 0);
        }

        if (imm != null && imm.isActive(code)) {
            imm.hideSoftInputFromWindow(code.getWindowToken(), 0);
        }
    }


    public void ApiVerificationCode(final String phoneNum) {
        final Dialog dialog = DialogUtil.getWaitDialog(getContext(), "发送中...");
        dialog.show();
        Call<BaseDTO> call = getRequestApi().verificationCode2(phoneNum);
        autoClose(call);
        call.enqueue(new Callback<BaseDTO>() {
            @Override
            public void onResponse(Call<BaseDTO> call, Response<BaseDTO> response) {
                dialog.dismiss();
                BaseDTO baseDTO = response.body();
                if (response.isSuccessful() && baseDTO != null) {
                    if (baseDTO.isSuccessful()) {
                        _handler.sendEmptyMessage(COUNT_START);

                    } else {
                        ToastUtil.showToast(baseDTO.getMsg());
                    }
                } else {
                    ToastUtil.showToast("数据异常");
                }
            }

            @Override
            public void onFailure(Call<BaseDTO> call, Throwable t) {
                dialog.dismiss();
                ToastUtil.showToast("网络故障");

            }
        });
    }


    @OnClick({R.id.bt_regain, R.id.bt_register})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_regain:
                ApiVerificationCode(_phoneNum);
                hideIme();

                break;
            case R.id.bt_register:
                if (StringUtils.isEmpty(code.getVerifyCodeStr())) {
                    ToastUtil.showToast("请输入验证码");
                    return;
                }
                String etPassWord = etPassword.getText().toString().trim();

                if (StringUtils.isEmpty(etPassWord)||etPassWord.length()<6) {
                    ToastUtil.showToast("请输入正确密码");
                    return;
                }

                if (!etPassword.getText().toString().equals(etPasswordConfirm.getText().toString
                        ())) {
                    ToastUtil.showToast("两次输入密码不一致");
                    return;
                }
                ApiModifyPassword();
                break;
            default:
                break;
        }
    }


}
